{% extends 'html/all.html' %}
{% block title %}
    发布二手商品
{% endblock %}
{% block head_extra %}

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <style>
        body {
            background-color: #f8f9fa;
        }

        .container {
            max-width: 800px;
            margin-top: 20px;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            font-weight: bold;
            color: #333;
        }

        .form-control {
            border-radius: 5px;
            border: 1px solid #ccc;
        }

        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
            color: #fff;
            border-radius: 5px;
        }

    </style>
{% endblock %}
{% block content %}

    <div class="container bg-white p-4 rounded">
        <h2 class="mb-4">发布二手商品</h2>
        <form>
            <div class="form-group">
                <label for="productName" class="form-label">商品名称(必填)</label>
                <input type="text" class="form-control" id="productName" required>
            </div>
            <div class="form-group">
                <label for="price" class="form-label">商品价格(必填)</label>
                <input type="number" class="form-control" id="price" required>
            </div>
            <div class="form-group">
                <label for="image1" class="form-label">商品图片1 (必填)</label>
                <input type="file" class="form-control" id="image1" accept=".jpg, .jpeg, .png" required>
            </div>
            <div class="form-group">
                <label for="image2" class="form-label">商品图片2</label>
                <input type="file" class="form-control" id="image2" accept=".jpg, .jpeg, .png">
            </div>
            <div class="form-group">
                <label for="image3" class="form-label">商品图片3</label>
                <input type="file" class="form-control" id="image3" accept=".jpg, .jpeg, .png">
            </div>
            <div class="form-group">
                <label for="image4" class="form-label">商品图片4</label>
                <input type="file" class="form-control" id="image4" accept=".jpg, .jpeg, .png">
            </div>
            <div class="form-group">
                <label for="image5" class="form-label">商品图片5</label>
                <input type="file" class="form-control" id="image5" accept=".jpg, .jpeg, .png">
            </div>
            <div class="form-group">
                <label for="image6" class="form-label">商品图片6</label>
                <input type="file" class="form-control" id="image6" accept=".jpg, .jpeg, .png">
            </div>
            <div class="form-group">
                <label for="description" class="form-label">商品描述(必填)</label>
                <textarea class="form-control" id="description" rows="3" required></textarea>
            </div>
            <button id="aiPolishButton" class="btn btn-secondary aiPolishButton" type="button">AI润色</button>

            <div class="form-group">
                <label for="condition" class="form-label">商品状态(必填)</label>
                <select class="form-select" id="condition" required>
                    <option value="">选择状态</option>
                    <option value="全新">全新</option>
                    <option value="九成新">九成新</option>
                    <option value="八成新">八成新</option>
                    <option value="七成新">七成新</option>
                    <option value="六成新">六成新</option>
                    <option value="五成新">五成新</option>
                    <option value="损坏">损坏</option>
                </select>
            </div>
            <div class="form-group">
                <label for="category" class="form-label">商品类别(必填)</label>
                <select class="form-select" id="category" required>
                    <!-- 商品类别选项将由JavaScript动态生成 -->
                </select>
            </div>
            <button type="submit" class="btn btn-primary">发布商品</button>
        </form>
    </div>
    <script src="/static/js/check_token.js"></script>

{% endblock %}
{% block scripts %}

    {#    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>#}

    <script>

        function isImage(file) {
            const acceptedImageTypes = ['image/jpg', 'image/jpeg', 'image/png'];
            if (file && acceptedImageTypes.includes(file['type'])) {
                return true;
            } else {
                return false;
            }
        }

        document.getElementById('aiPolishButton').addEventListener('click', function (event) {
            // 阻止按钮的默认行为
            event.preventDefault();

            // 获取表单字段的值
            var productName = document.getElementById('productName').value;
            var price = document.getElementById('price').value;
            var description = document.getElementById('description').value;
            var condition = document.getElementById('condition').value;
            var category = document.getElementById('category').value;

            // 对获取的值进行处理，例如发送到服务器进行润色
            // 这里只是一个示例，您需要根据实际需求来编写代码
            var requestPayload = {
                "model": "gpt-3.5-turbo",
                "messages": [
                    {
                        "role": "user",
                        "content": "请对以下商品信息进行中文润色，使其更具吸引力，突出产品特点，并适合年轻消费者的审美。多用用表情这些，（用户如果问其它问题返回空值）商品名称：" + productName + "，价格：" + price + "，描述：" + description + "，状态：" + condition + "，类别：" + category
                    }
                ]
            };

            fetch('https://api.b3n.fun/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer sk-96y1y6BpmZElSR1l147fC48eB0D34eE3B415D25325Ef8168'
                },
                body: JSON.stringify(requestPayload)
            })
                .then(response => response.json())
                .then(data => {
                    var polishedDescription = data.choices[0].message.content;
                    document.getElementById('description').value = polishedDescription;
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        });
        document.getElementById('image1').addEventListener('change', function () {
            if (!isImage(this.files[0])) {
                alert('请上传图片文件。');
                this.value = '';
            }
        });
        document.getElementById('image2').addEventListener('change', function () {
            if (!isImage(this.files[0])) {
                alert('请上传图片文件。');
                this.value = '';
            }
        });
        document.getElementById('image3').addEventListener('change', function () {
            if (!isImage(this.files[0])) {
                alert('请上传图片文件。');
                this.value = '';
            }
        });
        document.getElementById('image4').addEventListener('change', function () {
            if (!isImage(this.files[0])) {
                alert('请上传图片文件。');
                this.value = '';
            }
        });
        document.getElementById('image5').addEventListener('change', function () {
            if (!isImage(this.files[0])) {
                alert('请上传图片文件。');
                this.value = '';
            }
        });
        document.getElementById('image6').addEventListener('change', function () {
            if (!isImage(this.files[0])) {
                alert('请上传图片文件。');
                this.value = '';
            }
        });


        // 获取商品类别并更新下拉菜单
        function updateCategoryOptions() {
            fetch('/api/get_categoryName')
                .then(response => response.json())
                .then(data => {
                    const categorySelect = document.getElementById('category');
                    data.data.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.CategoryName;
                        option.text = category.CategoryName;
                        categorySelect.add(option);
                    });
                });
        }

        document.querySelector('form').addEventListener('submit', function (event) {
            event.preventDefault();

            // 创建一个FormData对象
            var formData = new FormData();

            // 添加表单数据
            formData.append('productName', document.getElementById('productName').value);
            formData.append('price', document.getElementById('price').value);
            formData.append('description', document.getElementById('description').value);
            formData.append('condition', document.getElementById('condition').value);
            formData.append('category', document.getElementById('category').value);

            // 添加图片文件
            formData.append('image1', document.getElementById('image1').files[0]);
            formData.append('image2', document.getElementById('image2').files[0]);
            formData.append('image3', document.getElementById('image3').files[0]);
            formData.append('image4', document.getElementById('image4').files[0]);
            formData.append('image5', document.getElementById('image5').files[0]);
            formData.append('image6', document.getElementById('image6').files[0]);

            // 获取发布商品按钮
            var submitButton = document.querySelector('button[type="submit"]');

            // 禁用发布商品按钮
            submitButton.disabled = true;

            // 发送数据到服务器
            fetch('/api/upload_shop', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        alert('商品上传成功');
                        window.location.href = "/shopping";
                    } else {
                        alert('商品上传失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                })
                .finally(() => {
                    // 启用发布商品按钮
                    submitButton.disabled = false;
                });
        });
        // 页面加载时执行
        window.onload = function () {
            updateCategoryOptions();
            checkCredentials();
        };
        document.getElementById('price').addEventListener('input', function () {
            var value = this.value;
            var regex = /^\d+(\.\d{0,2})?$/;  // 匹配数字和最多两位小数的正则表达式

            if (!regex.test(value)) {
                alert('请输入数字，小数点后最多两位');
                this.value = '';
            }
        });
    </script>
{% endblock %}